/*
* @Author: liqs
* @Date:   2021/10/25 9:44
 */
package ipfs

import (
	"bytes"
	"github.com/ipfs/go-ipfs-api"
	"github.com/pkg/errors"
	"io/ioutil"
	"log"
)

type IpfsShell struct {
	*shell.Shell
}

func (she *IpfsShell) Init(ip string, port string) (err error) {
	shell := shell.NewShell(ip + ":" + port)
	if shell == nil {
		return errors.WithMessage(err, "creat ipfs shell failed ")
	}
	she.Shell = shell
	return nil
}

func (shell *IpfsShell) UploadToIPFS(inter interface{}) (hashid string, err error) {
	var hash string
	switch inter.(type) {
	case string:
		hash, err = shell.Shell.Add(bytes.NewBufferString(inter.(string)))
		if err != nil {
			return "", errors.WithMessage(err, "Upload Str IPFS error : ")
		}
	case []byte:
		hash, err = shell.Shell.Add(bytes.NewReader(inter.([]byte)))
		if err != nil {
			return "", errors.WithMessage(err, "Upload Byte IPFS error : ")
		}
	default:
		log.Fatal("UploadToIPFS type is only string or []byte")
	}
	return hash, err
}

// if filePath is a file , upload the file
// if filePath is a directory , upload all files under the filepath
func (shell *IpfsShell) UploadFileToIPFS(filePath string) (addLink string, err error) {
	addLink, err = shell.Shell.AddDir(filePath)
	if err != nil {
		return "", errors.WithMessage(err, "Upload File To IPFS error : ")
	}
	return addLink, err
}

func (shell *IpfsShell) DownloadFormIPFS(hashId string) (byte []byte, err error) {

	cat, err := shell.Shell.Cat(hashId)
	if err != nil {
		return byte, errors.WithMessage(err, "Download Form IPFS error : ")
	}
	body, err := ioutil.ReadAll(cat)
	if err != nil {
		return byte, errors.WithMessage(err, "ioutil ReadAll error : ")
	}

	return body, err
}
